#include "StdAfx.h"
#include "Global.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <windows.h>
using namespace std;

Global::Global(void)
{
}

Global::~Global(void)
{
}



std::wstring s2ws(const std::string s)
{
	std::wstring result;
    setlocale(LC_ALL, "chs"); 
    const char* _Source = s.c_str();
    size_t _Dsize = s.size() + 1;
    wchar_t *_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 0, _Dsize);
	size_t n;
    //mbstowcs_s(_Dest,_Source,_Dsize);
	mbstowcs_s(&n,_Dest,_Dsize,_Source,_Dsize);
    result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, "C");

	return result;
}


//Converting a WChar string to a Ansi string
std::string WChar2Ansi(LPCWSTR pwszSrc)
{
	int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
	if (nLen<= 0) return std::string("");
	char* pszDst = new char[nLen];
	if (NULL == pszDst) return std::string("");
	WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
	pszDst[nLen -1] = 0;
	std::string strTemp(pszDst);
	delete [] pszDst;
	return strTemp;
}
string wstring_to_string(wstring& inputws){ return WChar2Ansi(inputws.c_str()); }
//Converting a Ansi string to WChar string
std::wstring Ansi2WChar(LPCSTR pszSrc, int nLen)
{
	int nSize = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pszSrc, nLen, 0, 0);
	if(nSize <= 0) return NULL;
	WCHAR *pwszDst = new WCHAR[nSize+1];
	if( NULL == pwszDst) return NULL;
	MultiByteToWideChar(CP_ACP, 0,(LPCSTR)pszSrc, nLen, pwszDst, nSize);
	pwszDst[nSize] = 0;
	if( pwszDst[0] == 0xFEFF) // skip Oxfeff
		for(int i = 0; i < nSize; i ++) 
			pwszDst[i] = pwszDst[i+1]; 
	wstring wcharString(pwszDst);
	delete pwszDst;
	return wcharString;
}
std::wstring string_to_wstring(const string& s){ return Ansi2WChar(s.c_str(),s.size());}

std::string CString_to_string(const CString &strSrc)
{
#ifdef _UNICODE
	std::string resultString = WChar2Ansi((LPCWSTR)strSrc); 
#else
	std::string resultString((LPCSTR)strSrc);
#endif
	return resultString; 
}


UINT CString_to_UINT(const CString & value)
{
	UINT data=0;
	if(value.Find(_T("0x"))==0)
		_stscanf_s((LPCTSTR)value,_T("%x"),&data);
	else
		_stscanf_s((LPCTSTR)value,_T("%d"),&data);
	return data;
}

